home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18026 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  66 lines

  1. Path: news.halcyon.com!usenet
  2. From: normanb@halcyon.com (Norm Bryar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Pointer to Functions and Calls thereof??
  5. Date: Thu, 18 Apr 1996 15:58:15 GMT
  6. Organization: Northwest Nexus Inc.
  7. Message-ID: <4l5op9$bls@news.halcyon.com>
  8. References: <Dq017E.DL6@latcs1.lat.oz.au>
  9. NNTP-Posting-Host: blv-pm3-ip12.halcyon.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. woelkerl@lion.cs.latrobe.edu.au (Eric Woelkerling) wrote:
  13.  
  14. >    I'm having some trouble getting a pointer to a function to work...
  15.  
  16. >    So far - I've only got as far as..
  17.  
  18. >    void    func1(void){various bits}
  19. >    void    func2(void){various bits}
  20.  
  21. >    void    main()
  22. >    {    void    *a[1];
  23.  
  24. >        a[0]=func1;
  25. >        a[1]=func2;
  26.  
  27. >        (*a[0])();
  28. >        (*a[1])();
  29. >    }
  30.  
  31. > ...
  32. >    Please email me directly..        Thanks!
  33. >    Eric Woelkerling..
  34. >    woelkerl@lion.lat.oz.au
  35.  
  36.  
  37. Eric;
  38.     C++ likes type-safety.  First thing I'd do is typedef the function
  39. pointers you will be putting into an array, an array of that type, of
  40. course.  Then you can call the functions with (a[n])(args).
  41.  
  42.     Lastly, your array was defined as one element, but you put in two. 
  43.  
  44.  
  45. typedef void (*fptr)(void);
  46.  
  47. void    func1(void) 
  48. { cout << "func1\n"; }
  49. void    func2(void)
  50. { cout << "func2\n"; }
  51.  
  52. void    main()
  53. {    
  54.     fptr    a[2];
  55.  
  56.     a[0]=func1;
  57.     a[1]=func2;
  58.  
  59.     (a[0])( );  // calls func1
  60.     (a[1])( );  // calls func2
  61. }
  62.  
  63. Good luck.
  64.                 --Norm 
  65.  
  66.